package fr.mathis.ouestcharlie;

import java.util.ArrayList;
import java.util.HashMap;

import uk.co.senab.photoview.PhotoViewAttacher;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class GameActivity extends SherlockActivity implements OnItemClickListener {

	private static final int MENU_SOLUTION = 1;
	int numGame = -1;
	float indexX = 0.0f;
	float indexY = 0.0f;
	ArrayList<HashMap<String, String>> resultats;
	float defaultDensity = 480.0f;
	float currentDensity = 160.0f;
	PhotoViewAttacher mAttacher;
	ArrayList<HashMap<String, String>> listItem;
	public ArrayAdapter<String> adapter;
	BitmapDrawable bDrawable;
	GridView grid;
	MyBaseAdapter mSchedule;

	DrawerLayout mDrawerLayout;
	ActionBarDrawerToggle mDrawerToggle;
	boolean showMenu;
	String actionBarSubtitle;
	int levelLoading = -1;
	BitmapCacheManager bcm;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game);

		bcm = new BitmapCacheManager(getApplicationContext());
		initDrawer();
		if (this.getIntent().getStringExtra("num") != null) {
			numGame = Integer.parseInt(this.getIntent().getStringExtra("num"));
		} else {
			numGame = ToolsBDD.getInstance(this).getLastGame(getApplicationContext());
		}
		new LoadPage().execute();

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		currentDensity = metrics.densityDpi;

		getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.ab_background_pattern));
	}

	private void initDrawer() {
		getSupportActionBar().setDisplayShowTitleEnabled(true);

		if (findViewById(R.id.isTablet) == null) {
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		}

		if (findViewById(R.id.drawer_layout) != null) {
			mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
			mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

			showClosedIcon();
			mDrawerToggle = new ActionBarDrawerToggle(GameActivity.this, mDrawerLayout, R.drawable.ic_drawer, R.string.s5, R.string.s6) {
				public void onDrawerClosed(View view) {
					showClosedIcon();
					supportInvalidateOptionsMenu();
				}

				public void onDrawerOpened(View drawerView) {
					showOpenedIcon();
					supportInvalidateOptionsMenu();
				}
			};

			mDrawerLayout.setDrawerListener(mDrawerToggle);
		}
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		if (mDrawerToggle != null)
			mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (mDrawerToggle != null)
			mDrawerToggle.onConfigurationChanged(newConfig);

	}

	private void showClosedIcon() {
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH && findViewById(R.id.isTablet) == null) {
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		}
		showMenu = true;
		supportInvalidateOptionsMenu();
		getSupportActionBar().setSubtitle(actionBarSubtitle);
	}

	private void showOpenedIcon() {
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH && findViewById(R.id.isTablet) == null) {
			getSupportActionBar().setDisplayHomeAsUpEnabled(false);
		}
		showMenu = false;
		supportInvalidateOptionsMenu();
		if (getSupportActionBar().getSubtitle() != null) {
			actionBarSubtitle = getSupportActionBar().getSubtitle().toString();
		}
		getSupportActionBar().setSubtitle(null);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (findViewById(R.id.isTablet) != null)
			showMenu = true;
		menu.findItem(MENU_SOLUTION).setVisible(showMenu);
		return super.onPrepareOptionsMenu(menu);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_SOLUTION, 0, R.string.solution).setIcon(R.drawable.action_about).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		return true;
	}

	public boolean onMenuItemSelected(int featureId, MenuItem item) {

		if (mDrawerToggle != null && mDrawerToggle.onOptionsItemSelected(Tools.getMenuItem(item))) {
			return true;
		}

		int itemId = item.getItemId();
		switch (itemId) {
		case MENU_SOLUTION:
			Intent videoClient = new Intent(Intent.ACTION_VIEW);
			videoClient.setData(Uri.parse(ToolsPartie.getYoutubeUrl(numGame, getApplicationContext())));
			startActivity(videoClient);
			return true;
		}

		return true;
	}

	private void closeDrawer() {
		if (mDrawerLayout != null)
			mDrawerLayout.closeDrawer(GravityCompat.START);
	}

	private class LoadPage extends AsyncTask<Void, String, Void> {
		ProgressDialog mProgressDialog;
		ImageView iv;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (CongratzActivity.congratzScreen == null) {
				mProgressDialog = new ProgressDialog(GameActivity.this);
				mProgressDialog.setMessage(getApplicationContext().getResources().getString(R.string.loadingscreen));
				mProgressDialog.setCancelable(false);
				mProgressDialog.show();
			}
		}

		@Override
		protected Void doInBackground(Void... arg0) {

			try {

				resultats = ToolsPartie.initRes(GameActivity.this);

				if (iv == null)
					iv = (ImageView) findViewById(R.id.imgGame);
				Resources res = getResources();
				bDrawable = ToolsPartie.getImage(numGame, res, GameActivity.this);

				if (listItem == null) {
					listItem = new ArrayList<HashMap<String, String>>();
					HashMap<String, String> map;

					for (int i = 0; i < ToolsPartie.NB_GAMES; i++) {
						map = new HashMap<String, String>();
						map.put("id", i + "");
						if (ToolsBDD.getInstance(GameActivity.this).checkPartie(i + "")) {
							map.put("img", "" + ToolsPartie.getResThumbnail(i));
							map.put("unlock", "1");
						} else {
							map.put("img", "" + ToolsPartie.getResThumbnail(i));
							map.put("unlock", "0");
						}
						map.put("text", ToolsPartie.getTitle(i, getApplicationContext()));

						listItem.add(map);
					}
				}
			} catch (OutOfMemoryError e) {
				listItem = null;
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			actionBarSubtitle = ToolsPartie.getTitle(numGame, getApplicationContext()) + " - " + "\u2606" + (numGame >= 10 ? "\u2606" : "") + (numGame >= 20 ? "\u2606" : "");
			getSupportActionBar().setSubtitle(actionBarSubtitle);

			if (CongratzActivity.congratzScreen == null) {
				if (mProgressDialog != null && mProgressDialog.isShowing())
					mProgressDialog.dismiss();
			} else {
				if (CongratzActivity.congratzScreen != null)
					CongratzActivity.congratzScreen.finish();
				CongratzActivity.congratzScreen = null;
			}

			if (listItem == null) {
				Toast.makeText(getApplicationContext(), R.string.s4, Toast.LENGTH_LONG).show();
				finish();
			} else {
				if (grid == null) {
					grid = (GridView) findViewById(R.id.gridView1);
					mSchedule = new MyBaseAdapter(GameActivity.this, listItem);
					grid.setAdapter(mSchedule);
					grid.setOnItemClickListener(GameActivity.this);
					grid.setSelection(numGame);
				} else {
					listItem.get(numGame).put("unlock", "1");
					mSchedule.notifyDataSetChanged();
				}

				iv.setImageDrawable(bDrawable);
				iv.setBackgroundColor( numGame == 0 ? Color.parseColor("#292639") : new ColorArt(bDrawable.getBitmap()).getBackgroundColor());
				imgWidth = bDrawable.getIntrinsicWidth();
				imgHeight = bDrawable.getIntrinsicHeight();
				mAttacher = new PhotoViewAttacher(iv);
				mAttacher.setOnPhotoTapListener(new PhotoTapListener());

				final LinearLayout llInfo = (LinearLayout) findViewById(R.id.llInfo);

				if (DataManager.GetMemorizedValueBoolean("tuto", getApplicationContext())) {
					llInfo.setVisibility(View.GONE);
				} else {
					llInfo.setVisibility(View.VISIBLE);
					findViewById(R.id.btnTuto).setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							DataManager.MemorizeValue("tuto", true, getApplicationContext());
							llInfo.setVisibility(View.GONE);

							AlphaAnimation alpha = new AlphaAnimation(1.0F, 0.0F);
							alpha.setDuration(1000);
							alpha.setFillAfter(true);
							alpha.setAnimationListener(new AnimationListener() {

								@Override
								public void onAnimationStart(Animation animation) {
								}

								@Override
								public void onAnimationRepeat(Animation animation) {
								}

								@Override
								public void onAnimationEnd(Animation animation) {
									llInfo.setVisibility(View.GONE);
								}
							});
							llInfo.startAnimation(alpha);

						}
					});
				}
			}
			levelLoading = -1;
		}
	}

	int imgWidth = 0;
	int imgHeight = 0;

	private class PhotoTapListener implements OnPhotoTapListener {

		@Override
		public void onPhotoTap(View view, float x, float y) {
			int pixelX, pixelY = 0;
			pixelX = (int) (imgWidth * x);
			pixelY = (int) (imgHeight * y);
			checkWinner(pixelX, pixelY);
		}
	}

	public void checkWinner(float x, float y) {
		float cc = (defaultDensity / currentDensity);
		float minX, minY, maxX, maxY;
		minY = Float.parseFloat(resultats.get(numGame).get("top")) / cc;
		minX = Float.parseFloat(resultats.get(numGame).get("left")) / cc;
		maxY = Float.parseFloat(resultats.get(numGame).get("bottom")) / cc;
		maxX = Float.parseFloat(resultats.get(numGame).get("right")) / cc;

		if (x > minX && x < maxX && y < maxY && y > minY) {
			congratsWinner();
		}
	}

	private void loadLevel(int n) {
		levelLoading = n;
		numGame = n;
		// new LoadLevel().execute();
		new LoadPage().execute();
	}

	public void loadNextLevel() {
		loadLevel(numGame + 1);
	}

	// class LoadLevel extends AsyncTask<Void, Void, Void> {
	// ImageView iv;
	// ProgressDialog mProgressDialog;
	//
	// @Override
	// protected void onPreExecute() {
	// super.onPreExecute();
	// if (CongratzActivity.congratzScreen == null) {
	// mProgressDialog = new ProgressDialog(GameActivity.this);
	// mProgressDialog.setMessage(getApplicationContext().getResources().getString(R.string.loadingscreen));
	// mProgressDialog.setCancelable(false);
	// mProgressDialog.show();
	// }
	// }
	//
	// @Override
	// protected Void doInBackground(Void... params) {
	// iv = (ImageView) findViewById(R.id.imgGame);
	// try {
	// Resources res = getResources();
	// listItem.get(numGame).put("img", "" + ToolsPartie.getResThumbnail(numGame));
	// bDrawable.getBitmap().recycle();
	// bDrawable = null;
	// bDrawable = ToolsPartie.getImage(numGame, res, GameActivity.this);
	// } catch (OutOfMemoryError e) {
	// bDrawable = null;
	// e.printStackTrace();
	// }
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(Void result) {
	//
	// actionBarSubtitle = ToolsPartie.getTitle(numGame, getApplicationContext()) + " - " + "\u2606" + (numGame >= 10 ? "\u2606" : "") + (numGame >= 20 ? "\u2606" : "");
	// getSupportActionBar().setSubtitle(actionBarSubtitle);
	// if (CongratzActivity.congratzScreen == null) {
	// if (mProgressDialog != null && mProgressDialog.isShowing())
	// mProgressDialog.dismiss();
	// } else {
	// if (CongratzActivity.congratzScreen != null)
	// CongratzActivity.congratzScreen.finish();
	// }
	// CongratzActivity.congratzScreen = null;
	//
	// if (bDrawable != null) {
	// listItem.get(numGame).put("unlock", "1");
	//
	// mSchedule.notifyDataSetChanged();
	// iv.setImageDrawable(bDrawable);
	// imgWidth = bDrawable.getIntrinsicWidth();
	// imgHeight = bDrawable.getIntrinsicHeight();
	// iv.setBackgroundColor(new ColorArt(bDrawable.getBitmap()).getBackgroundColor());
	// mAttacher = new PhotoViewAttacher(iv);
	// mAttacher.setOnPhotoTapListener(new PhotoTapListener());
	// }
	//
	// if (bDrawable == null) {
	// Toast.makeText(getApplicationContext(), R.string.s4, Toast.LENGTH_LONG).show();
	// finish();
	// } else {
	// closeDrawer();
	// }
	// levelLoading = -1;
	// }
	// }

	private void congratsWinner() {
		ToolsBDD.getInstance(this).insertPartie((numGame + 1) + "");

		CongratzActivity.listener = GameActivity.this;
		Intent i = new Intent(GameActivity.this, CongratzActivity.class);
		Bundle b = new Bundle();
		b.putBoolean("showContinue", numGame < (ToolsPartie.NB_GAMES - 1));
		i.putExtras(b);
		startActivity(i);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		if (ToolsBDD.getInstance(GameActivity.this).checkPartie(arg2 + "")) {

			if (levelLoading != -1) {

			} else {
				closeDrawer();
				if (numGame != arg2)
					startGame(arg2);
			}

		} else
			Toast.makeText(this, R.string.notpossible, Toast.LENGTH_SHORT).show();
	}

	protected void startGame(int n) {
		loadLevel(Integer.parseInt(listItem.get(n).get("id")));
	}

	class MyBaseAdapter extends BaseAdapter {

		ArrayList<HashMap<String, String>> _items;

		public MyBaseAdapter(GameActivity gameActivity, ArrayList<HashMap<String, String>> listItem) {
			_items = listItem;
		}

		@Override
		public int getCount() {
			return _items.size();
		}

		@Override
		public Object getItem(int position) {
			return _items.get(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;

			if (v == null) {
				v = LayoutInflater.from(GameActivity.this).inflate(R.layout.griditem, null);
			}

			TextView tv = (TextView) v.findViewById(R.id.textView1);
			tv.setText(_items.get(position).get("text"));

			int idImage = Integer.parseInt(_items.get(position).get("img"));
			ImageView iv = (ImageView) v.findViewById(R.id.imageView1);
			iv.setImageBitmap(null);

			iv.setTag(_items.get(position).get("unlock") + idImage);
			bcm.loadBitmap(_items.get(position).get("unlock") + idImage, iv);

			if (_items.get(position).get("unlock").compareTo("0") == 0)
				v.findViewById(R.id.imageViewLock).setVisibility(View.VISIBLE);
			else
				v.findViewById(R.id.imageViewLock).setVisibility(View.GONE);

			final int p = position;
			v.findViewById(R.id.overlay).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					GameActivity.this.onItemClick(null, null, p, 0);
				}
			});

			LinearLayout ll = (LinearLayout) v.findViewById(R.id.diffContainer);
			if (position < 10) {
				ll.getChildAt(0).setVisibility(View.VISIBLE);
				ll.getChildAt(1).setVisibility(View.GONE);
				ll.getChildAt(2).setVisibility(View.GONE);
			} else if (position < 20) {
				ll.getChildAt(0).setVisibility(View.VISIBLE);
				ll.getChildAt(1).setVisibility(View.VISIBLE);
				ll.getChildAt(2).setVisibility(View.GONE);
			} else {
				ll.getChildAt(0).setVisibility(View.VISIBLE);
				ll.getChildAt(1).setVisibility(View.VISIBLE);
				ll.getChildAt(2).setVisibility(View.VISIBLE);
			}

			v.findViewById(R.id.imageView2).setVisibility(numGame == position ? View.VISIBLE : View.GONE);

			return v;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}
	}

}
